package com.shop.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.entity.Product;
import com.shop.service.ProductService;
import com.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author D
 * @since 2023-03-11 03:02:04
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取分页商品列表
     * @param page 页码
     * @param pageSize 页面大小
     * @param typeId 商品类型ID
     * @return 分页商品列表
     */
    @RequestMapping("/getPageList")
    public Page<Product> getPageList(Integer page, Integer pageSize, Integer typeId) {
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        if (typeId == null) {
            typeId = 0;
        }
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        String cachePage = typeId + "-" + page + "-product-list-by-type-page";
        Page<Product> productListByTypePage = (Page<Product>) opsForHash.get("productListByTypePage", cachePage);
        if (productListByTypePage == null) {
            productListByTypePage = productService.getPageList(page, pageSize, typeId);
            opsForHash.put("productListByTypePage", cachePage, productListByTypePage);
            redisTemplate.expire("productListByTypePage", 1, TimeUnit.DAYS);
        }
        return productListByTypePage;
    }
    /**
     * 获取商品详情
     * @param id 商品ID
     * @return 商品详情
     */
    @RequestMapping("/toDetail")
    public Product toDetail(Integer id) {
        String cacheIdKey = "productId:" + id;
        final int productDetailOverTimeOut = 10;
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Product product = (Product) opsForValue.get(cacheIdKey);
        if (product == null) {
            product = productService.getById(id);
            opsForValue.set(cacheIdKey, product, productDetailOverTimeOut, TimeUnit.MINUTES);
        }

        return product;
    }


}

